package com.trainoo.novel.service;

import com.trainoo.novel.constant.NovelConstant;
import com.trainoo.novel.crawler.NovelCrawlerAdapter;
import com.trainoo.novel.util.SessionUtil;
import com.trainoo.novel.util.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class NovelAdapterService {

    private static Logger logger = LoggerFactory.getLogger(NovelAdapterService.class);

    @Value("${default.source.website}")
    private String DEFAULT_ADAPTER;

    public static NovelCrawlerAdapter getAvailNovelAdapter() {
        // 这里不能直接new对象，必须从spring容器里面获取。否则DEFAULT_ADAPTER注入无效
        NovelAdapterService service = SpringContextHolder.getBean(NovelAdapterService.class);
        try {
            HttpSession session = SessionUtil.getSession();
            String webSiteName = (String) session.getAttribute(NovelConstant.WEB_SOURCE);
            if (null != webSiteName && !"".equals(webSiteName)) {
                logger.info("获取到Adapter[{}]", webSiteName);
                return service.getAvailNovelAdapter(webSiteName);
            }else{
                logger.info("未能获取到Adapter，使用默认配置。");
                return service.getDefaultAvailNovelAdapter();
            }
        } catch (Exception e) {
            logger.error("获取Adapter时出现异常，使用默认配置。");
            return service.getDefaultAvailNovelAdapter();
        }
    }

    private NovelCrawlerAdapter getDefaultAvailNovelAdapter(){
        logger.info("使用默认配置源：{}", DEFAULT_ADAPTER);
        try {
            HttpSession session = SessionUtil.getSession();
            session.setAttribute(NovelConstant.WEB_SOURCE, DEFAULT_ADAPTER);
        }catch (Exception e){
            logger.error("设置默认源[{}]出现异常", DEFAULT_ADAPTER);
        }
        return getAvailNovelAdapter(DEFAULT_ADAPTER);
    }

    private NovelCrawlerAdapter getAvailNovelAdapter(String webSiteName) {
        String webSite = webSiteName.toLowerCase();
        try {
            // 注意此处约定所有的Adapter实现类命名规则为{webSiteName}NovelCrawler
            Object crawlerBean = SpringContextHolder.getBean(webSite + "NovelCrawler");
            if (crawlerBean instanceof NovelCrawlerAdapter) {
                return (NovelCrawlerAdapter) crawlerBean;
            } else {
                logger.error("未找到webSiteName为[{}]的Adapter", webSiteName);
                return null;
            }
        } catch (NoSuchBeanDefinitionException e) {
            logger.error("未找到webSiteName为[{}]的Adapter", webSiteName);
            return null;
        }
    }
}
